Number of 1 bits¶
Time: O(LogN)=O(32); Space: O(1); easy
Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).
Example 1:
Input: num = 11
Output: 3
Explanation:
Binary representation (as 32-bit integer): 00000000000000000000000000001011
[1]:
class Solution(object):
def hammingWeight(self, num) -> int:
"""
:type num: int
:rtype: int
"""
result = 0
while num:
num &= num - 1
result += 1
return result
[2]:
s = Solution1()
num = 11
assert s.hammingWeight(num) == 3